package cit.project.capeclear;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class DataBase {
	private static String DB_PATH = "/data/data/cit.project.capeclear/databases/";
	private static String DB_NAME = "cc_db";
	static InputStream myInput;
	Activity act;

	public DataBase(Activity activity) { 
		act = activity;
	}


	int readInternetVersion() throws MalformedURLException{
		String str = null;
		int version = 0;
		try {
			URL url = new URL("http://ccapp.web44.net/dbversion");

			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

			while ((str = in.readLine()) != null) {
				try{
					version=Integer.parseInt(str);
				}
				catch(NumberFormatException n){
					version=0;
				}
			}
			in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}

		return version;
	}


	boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();

		if (netInfo != null && netInfo.isConnectedOrConnecting()) 
			return true;

		else
			return false;
	}


	void dataBaseExist(){
		//checking if database exists if not, will be copied from the assets 
		//if(checkDataBase())
		//Toast.makeText(act.getBaseContext(), "DataBase exists", Toast.LENGTH_SHORT).show();
		//else{
		//Toast.makeText(act.getBaseContext(), "DataBase does not exist", Toast.LENGTH_SHORT).show();

		myInput = act.getResources().openRawResource(R.raw.cc_db);

		try {
			copyDataBase();
			//Toast.makeText(act.getBaseContext(), "DataBase copied from Mobile Storage", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	//}


	boolean checkDataBase(){

		SQLiteDatabase checkDB = null;
		try{
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
		} catch(SQLiteException e){
		}

		if(checkDB != null){
			checkDB.close();
		}

		return checkDB != null ? true : false;
	}


	void copyDataBase() throws IOException {

		File dir = new File(DB_PATH);
		if (!dir.exists()) dir.mkdir();
		String outFileName = DB_PATH + DB_NAME;
		OutputStream myOutput = new FileOutputStream(outFileName);

		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer))>0){
			myOutput.write(buffer, 0, length);
		}

		myOutput.flush();
		myOutput.close();
		myInput.close();

	}






}
